package cn.kgc.controller;

import cn.kgc.entity.MenuInfo;
import cn.kgc.entity.RoleInfo;
import cn.kgc.service.MenuService;
import cn.kgc.service.RoleService;
import cn.kgc.service.UserService;
import cn.kgc.entity.UserInfo;
import cn.kgc.vo.ResultVo;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @GetMapping("/login")
    public  String loginUi(){
        return  "login";
    }

    @GetMapping("/index")
    public  String index(){
        return  "index";
    }

    @GetMapping("/")
    public  String index1(){
        return  "redirect:/index";
    }


    @PostMapping("/login")
    @ResponseBody
    public ResultVo<Object> login(UserInfo user, HttpSession session){
        if( user==null || user.getPsw()==null || user.getUsername()==null){
            return new ResultVo<>(20001,"非法的入参",null);
        }
       UserInfo user1 = userService.login(user.getUsername(), user.getPsw());
       if(user1 !=null){
           session.setAttribute("kgcUser",user1);
           return new ResultVo<>(20000,"登录成功",null);
       }
        return new ResultVo<>(20001,"用户名或密码错误",null);
    }

    @GetMapping("/menu")
    @ResponseBody
    public  ResultVo<List<MenuInfo>>  getAllMenu(@RequestParam(name = "id",required = false)
                                                             String id){
        Integer  pid=0;
        if(id ==null)
            pid=0;
        else {
              pid=Integer.parseInt(id.split("\\|")[0]);
            }
        System.out.println("id:"+pid);
        List<MenuInfo> list = menuService.getMenu(pid);
        return  new ResultVo<>(20000,"查询成功",list);
    }

    @GetMapping("/role/view")
    public  String toRole(){
        return  "role";
    }

    @GetMapping("/role")
    @ResponseBody
    public ResultVo<Map<String,Object>>  getRole(@RequestParam("page") Integer pageNo,
                                             @RequestParam("rows") Integer pageSize){
        Page<List<RoleInfo>> role = roleService.getRole(pageNo, pageSize, null);
        Map<String,Object> data= new HashMap<>();
        data.put("total",role.getTotal());// 总记录数
        data.put("rows",role.getResult()); //页数
        return new ResultVo<>(20000,"查询成功",data);
    }

    @PostMapping("/role")
    @ResponseBody
    public  ResultVo<Object> addRole(RoleInfo roleInfo){
      //  System.out.println(roleInfo);
     roleService.addRole(roleInfo);
     return  new ResultVo<>(20000,"新增成功",null);
    }

    @PutMapping("/role")
    @ResponseBody
    public  ResultVo<Object> updateRole(RoleInfo roleInfo){
        System.out.println(roleInfo);
        roleService.updateRole(roleInfo);
        return  new ResultVo<>(20000,"修改成功",null);
    }

    @GetMapping("/role/{id}")
    @ResponseBody
    public  RoleInfo getRoleById(@PathVariable("id") Integer id){
        RoleInfo roleInfo= roleService.getRoleById(id);
       // return  new ResultVo<>(20000,"查询成功",roleInfo);
        return  roleInfo;
    }

    @DeleteMapping("/role")
    @ResponseBody
    public ResultVo<Object>  deleteRole(@RequestParam("ids") String ids){
        roleService.deleteRole(ids);
        return  new ResultVo<>(20000,"删除成功",null);
    }

    @GetMapping("/user/view")
    public  String toUser(){
        return  "user";
    }

    @GetMapping("/roles")
    @ResponseBody
    public  ResultVo<List<RoleInfo>>  getAllRoles(@RequestParam(name = "id",required = false)
                                                         String id){

        List<RoleInfo> list = roleService.getRoleById2();
        for (RoleInfo l:list){
            l.setText(l.getRoleName());
        }
        return  new ResultVo<>(20000,"查询成功",list);
    }

//分页查询用户
    @GetMapping("/user")
    @ResponseBody
    public ResultVo<Map<String,Object>>  getUser(@RequestParam("page") Integer pageNo,
                                                 @RequestParam("rows") Integer pageSize){
        Page<List<UserInfo>> user = userService.getUser(pageNo, pageSize,null);
        Map<String,Object> data= new HashMap<>();
        data.put("total",user.getTotal());// 总记录数
        data.put("rows",user.getResult()); //页数
        return new ResultVo<>(20000,"查询成功",data);
    }

    //新增用户
    @PostMapping("/user")
    @ResponseBody
    public  ResultVo<Object> addUser(UserInfo userInfo){
        String psw= toMD5(userInfo.getPsw());
        userInfo.setPsw(psw);
        userService.addUser(userInfo);
        return  new ResultVo<>(20000,"新增成功",null);
    }

//修改之前查询数据
    @GetMapping("/user/{id}")
    @ResponseBody
    public  UserInfo getUserById(@PathVariable("id") Integer id){
        UserInfo userInfo= userService.getRoleById(id);
        // return  new ResultVo<>(20000,"查询成功",roleInfo);
        return  userInfo;
    }
    @PutMapping("/user")
    @ResponseBody
    public  ResultVo<Object> updateUser(UserInfo userInfo){
       /* System.out.println(userInfo);
        roleService.updateRole(roleInfo);*/
        return  new ResultVo<>(20000,"修改成功",null);

    }

    @DeleteMapping("/user")
    @ResponseBody
    public ResultVo<Object>  deleteUser(@RequestParam("ids") String ids){
        userService.deleteUser(ids);
        return  new ResultVo<>(20000,"删除成功",null);
    }

//MD5加密
public static String toMD5(String str){
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes());
        byte[]byteDigest = md.digest();
        int i;
        StringBuffer buf = new StringBuffer("");
        for (int offset = 0; offset < byteDigest.length; offset++) {
            i = byteDigest[offset];
            if (i < 0)
                i += 256;
            if (i < 16)
                buf.append("0");
            buf.append(Integer.toHexString(i));
        }
        //32位加密
        return buf.toString();
        // 16位的加密
        //return buf.toString().substring(8, 24);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    }
}
